<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>视频录制</title>
    <style>
        html,
        body {
            margin: 0;
            position: relative;
        }
        video {
            width: 60%;       
            margin: auto;
            display: block;
            max-height: 400px;
        }
        .list{
            padding-left: 10px;
            color: #2440b3;
            cursor: pointer;
        }
        .f-player{
            position: fixed;
            right: 0;
            top: 40%;
            width: 60%;   
            display: none;   
        }

        .btn {
            font-weight: 700;
            color: #fff;
            
        }
    </style>
</head>
<body>
    <div>
        <video id="videoEL" controls autoplay></video>
    </div>
    <div style="text-align: center; margin-top: 10px;">
        <button id="btnRecord" class="btn" style="background-color: green;">录制</button>
        <button id="btnStop"  class="btn" style="background-color: red;">停止</button>
    </div>
    <hr>
    <div>
        录制视频列表：
    </div>
    <div id="list" class="list">
    </div>

    <video id="fplayer" class="f-player" autoplay controls></video>
    <script src="./idb-keyval.js"></script>
    <script>
        let mediaRecorder;
        async function init() {
            if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
                return console.log("getUserMedia not supported on your browser!")
            }
            try {
                const stream = await navigator.mediaDevices.getUserMedia({
                    video: { facingMode: "environment" },
                    audio: true
                })
                videoEL.srcObject = stream;
                mediaRecorder = new MediaRecorder(stream, { mimeType: "video/webm" });

            } catch (err) {
                alert(err);
                return console.error("error:", err);
            }
        };

        init();

        function startRecord(recorder) {
            var chunks = [];
            recorder.ondataavailable = function (e) {
                chunks.push(e.data);
            }

            recorder.onstop = async () => {
                var clipName = prompt('请输入视频的名字');
                var blob = new Blob(chunks, { 'type': 'audio/mp4;' });

                await idbKeyval.set(clipName + ".mp4", blob);
                listHistory();
            }
        }

        btnRecord.addEventListener("click", () => {
            startRecord(mediaRecorder);
            mediaRecorder.start();
        });

        btnStop.addEventListener("click", () => {
            mediaRecorder.stop();
        })


        async function playVideo(key) {
            const blob = await idbKeyval.get(key);

            fplayer.src = URL.createObjectURL(blob);
            fplayer.style.display = "block";
            fplayer.play();

        }

        async function listHistory() {
            list.innerHTML = null;
            const keys = await idbKeyval.keys();
            console.log("keys:", keys);

            keys.filter(k => k.endsWith(".mp4")).forEach(key => {
                const divEl = document.createElement("div");
                divEl.textContent = key;
                divEl.onclick = () => playVideo(key);

                list.appendChild(divEl);
            });
        }
        
        listHistory();
    </script>
</body>
</html>